#opencv 4.1.1.26


import cv2
import os
import time
import numpy as np
import VideoStream
from ReadIniConfig import ReadConfig
from ApiServer import HttpServer
from threading import Thread
import YoloDetect


#读取配置文件
data = ReadConfig()

### ---- INITIALIZATION ---- ###
# Define constants and initialize variables
## Camera settings
IM_WIDTH = int(data.get_config("video_width"))
IM_HEIGHT = int(data.get_config("video_height")) 

FRAME_RATE = 10

## Initialize calculated frame rate because it's calculated AFTER the first time it's displayed
frame_rate_calc = 1
freq = cv2.getTickFrequency()

## Define font to use
font = cv2.FONT_HERSHEY_SIMPLEX

camera_type=int(data.get_config("camera_type"))
camera_src=data.get_config("camera_src")

game_type=data.get_config("game_type")

server=HttpServer(9991,game_type)

Thread(target=server.Start,args=()).start()

# Initialize camera object and video feed from the camera. The video stream is set up
# as a seperate thread that constantly grabs frames from the camera feed. 
# See VideoStream.py for VideoStream class definition
## IF USING USB CAMERA INSTEAD OF PICAMERA,
## CHANGE THE THIRD ARGUMENT FROM 1 TO 2 IN THE FOLLOWING LINE:
videostream = VideoStream.VideoStream((IM_WIDTH,IM_HEIGHT),FRAME_RATE,camera_type,camera_src).start()
time.sleep(1) # Give the camera time to warm up



# 点是否在外包矩形内
def isPoiWithinBox(poi, sbox, toler=0.0001):
	# sbox=[[x1,y1],[x2,y2]]
	# 不考虑在边界上，需要考虑就加等号
	if poi[0] > sbox[0][0] and poi[0] < sbox[1][0] and poi[1] > sbox[0][1] and poi[1] < sbox[1][1]:
		return True
	if toler > 0:
		pass
	return False



cam_quit = 0 # Loop control variable

L1ptStart=None



#Opencv 识别图片
def OpencvDetect(image):
    if YoloDetect.IsBusy==1:
        YoloDetect.IsBusy=0
        try:
            yolo_result=YoloDetect.OpencvDetect(image)
            if (len(yolo_result) != 0):
                temp_cnts = []
                for i in range(len(yolo_result)):
                    yolo_item=yolo_result[i]
                    if not yolo_item["card_value"]=='':
                        card_name=""
                        card_value=""
                        if game_type=='bac':
                            if isPoiWithinBox(yolo_item["center"],poly):
                                card_name="p1"
                            elif isPoiWithinBox(yolo_item["center"],poly1):
                                card_name="p2"
                            elif isPoiWithinBox(yolo_item["center"],poly2):
                                card_name="p3"
                            elif isPoiWithinBox(yolo_item["center"],poly3):
                                card_name="p4"
                            elif isPoiWithinBox(yolo_item["center"],poly4):
                                card_name="p5"
                            elif isPoiWithinBox(yolo_item["center"],poly5):
                                card_name="p6"
                        elif game_type=='lh':
                            if isPoiWithinBox(yolo_item["center"],poly):
                                card_name="p1"
                            elif isPoiWithinBox(yolo_item["center"],poly1):
                                card_name="p2"
                
                        result_value=yolo_item["card_value"]
                        if(len(result_value)>=2 and card_name!=""):
                            #花色,数字
                            card_value={"suit":result_value[-1],"rank":result_value[0:-1]}
                            server.PostCardData(card_name,card_value)
        except Exception:
            pass
        YoloDetect.IsBusy=1
    else:
        pass
        

while cam_quit == 0:
    # Grab frame from video stream
    image = videostream.read()
    if image is  None:
        continue
    if len(image)==0:
        continue
    if L1ptStart==None and game_type=='bac':
        pic_width=image.shape[1]
        pic_height=image.shape[0]

        L1ptStart = (int(pic_width/4),0)
        L1ptEnd = (int(pic_width/4),int((pic_height/5)*3))
        
        L2ptStart = (int(pic_width/2),0)
        L2ptEnd = (int(pic_width/2),int(pic_height))
        
        L3ptStart = (int((pic_width/4)*3),0)
        L3ptEnd = (int((pic_width/4)*3),int((pic_height/5)*3))
        
        L4ptStart = (0,int((pic_height/5)*3))
        L4ptEnd = (int(pic_width),int((pic_height/5)*3))

        #P1
        poly = [[0, 0], [L1ptEnd[0],L1ptEnd[1]]]
        #P2因为L2是贯穿的
        poly1 = [[L1ptStart[0], L1ptStart[1]], [L2ptEnd[0],L2ptEnd[1]/5*3]]
        #P3
        poly2 = [[L2ptStart[0], L2ptStart[1]], [L3ptEnd[0],L3ptEnd[1]]]
        #P4
        poly3 = [[L3ptStart[0], L3ptStart[1]], [L4ptEnd[0],L4ptEnd[1]]]
        #P5
        poly4 = [[L4ptStart[0], L4ptStart[1]], [L2ptEnd[0],L2ptEnd[1]]]
        #P6
        poly5 = [[L2ptEnd[0],L2ptEnd[1]/5*3], [pic_width,pic_height]]
    elif L1ptStart==None and game_type=='lh':
        pic_width=image.shape[1]
        pic_height=image.shape[0]
        L1ptStart = (int(pic_width/2),0)
        L1ptEnd = (int(pic_width/2),pic_height)
        #P1
        poly = [[0, 0], [L1ptEnd[0],L1ptEnd[1]]]
        #P2因为L2是贯穿的
        poly1 = [[L1ptStart[0], L1ptStart[1]], [pic_width,pic_height]]
    t1 = cv2.getTickCount()    
    OpencvDetect(image)
    cv2.putText(image,"FPS: "+str(int(frame_rate_calc)),(10,26),font,0.7,(255,0,255),2,cv2.LINE_AA)


    
    if game_type=='lh' or game_type=='bac':
        #画辅助线
        # L1起点和终点的坐标
        point_color = (0, 255, 0) # BGR
        thickness = 1 
        lineType = 4
        cv2.line(image, L1ptStart, L1ptEnd, point_color, thickness, lineType)
    if  game_type=='bac':
        #L2起点和终点的坐标
        point_color = (0, 0, 225) # BGR
        thickness = 1 
        lineType = 8
        cv2.line(image, L2ptStart, L2ptEnd, point_color, thickness, lineType)
        #L3起点和终点的坐标
        point_color = (0, 255, 0) # BGR
        thickness = 1 
        lineType = 8
        cv2.line(image, L3ptStart, L3ptEnd, point_color, thickness, lineType)
        #L4起点和终点的坐标
        point_color = (0, 255, 225) # BGR
        thickness = 2 
        lineType = 8
        cv2.line(image, L4ptStart, L4ptEnd, point_color, thickness, lineType)


    # Finally, display the image with the identified cards!
    cv2.imshow("Card Detector",image)
    # Calculate framerate
    t2 = cv2.getTickCount()
    time1 = (t2-t1)/freq
    frame_rate_calc = 1/time1
    # Poll the keyboard. If 'q' is pressed, exit the main loop.
    key = cv2.waitKey(1) & 0xFF
    if key == ord("q"):
        # Close all windows and close the PiCamera video stream.
        cv2.destroyAllWindows()
        videostream.stop()
        server.Stop()

